<?php

namespace app\admin\controller;

use think\Controller;
use think\response\Jump;

class Cate extends Controller
{
    // use Jump;
    public function __construct()
    {
        parent::__construct();
        session_start();
        if(empty($_SESSION['username'])) {
            $this->wderror('http://127.0.0.1/bnstudy/public/index.php/admin/Admin/index', '请登录');die;
        }
        
         
    }
    public function index()
    {
        $cateRes = model('cate')->field('id, cate_name')->where('status', 1)->order('id desc')->select();
        $this->assign([
            'cateRes' => $cateRes
        ]);
        return view('list');
    }
    public function add()
    {
        if (request()->isPost()) {
            $cateModel = model('cate');
            if ($_FILES['icon']['tmp_name']) {
                $imgSrc = $this->upload('icon');
            } else {
                $this->error('未上传图标');
            }

            $add = $cateModel->save(['cate_name' => input('cate_name'), 'icon' => $imgSrc]);
            if ($add) {
                $this->success('添加成功', 'index');
            } else {
                $this->error('添加失败');
            }
        }
        return view();
    }
    //编辑
    public function edit()
    {
        $cateModel = model('Cate');
        $id = input('id');
        $cates = $cateModel->find($id);
        if (request()->isPost()) {
            $data = input('post.');
            if ($_FILES['icon']['tmp_name']) {
                //删除
                $oldImgSrc = '../public/static/api/uploads/' . $cates['icon'];
                if (file_exists($oldImgSrc)) {
                    unlink($oldImgSrc);
                }
                //上传
                $imgSrc = $this->upload('icon');
                $data['icon'] = $imgSrc;
            }
            $save = $cateModel->save($data, ['id' => $id]);
            if ($save !== false) {
                $this->success('修改成功', 'index');
            } else {
                $this->success('添加失败');
            }
        } else {
            $this->assign([
                'cates' => $cates
            ]);
            return view();
        }
    }
    //删除按钮
    public function del($id)
    {
        $del = model('Cate')->save(['status' => 0], ['id' => $id]);
        if ($del) {
            $this->success('删除成功', 'index');
        } else {
            $this->success('删除失败');
        }
    }
    //图片上传
    public function upload($imgName)
    {
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file($imgName);
        // 移动到框架应用根目录/uploads/ 目录下
        $uploadsSrc = '../public/static/api/uploads';
        $info = $file->move($uploadsSrc);
        if ($info) {
            return $info->getSaveName();
        } else {
            // 上传失败获取错误信息
            echo $file->getError();
        }
    }
}
